import { useState, useEffect } from 'react';
import { Card, List, Space, Button, Input, Select, Pagination, Checkbox, Upload } from 'antd';
import { SyncOutlined, UploadOutlined } from '@ant-design/icons';
import { connect, useIntl } from 'umi';
import UploadUtil from '@/components/UploadUtil';
import { GetFileExt } from '@/services/crud';
import request from '@/utils/request';

const apiURL = '/api/services/app/Attachment/';
const { Search } = Input;

const ViewPage = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [pageIndex, setPageIndex] = useState(1);
  const [pageSize, setPageSize] = useState(8);
  const [totalCount, setTotalCount] = useState(0);
  const [keywords, setKeywords] = useState('');
  const [fileExt, setFileExt] = useState([]);
  const [ext, setExt] = useState(null);
  const [selectId, setSelectId] = useState<any[]>([]);
  const [gutter, setGutter] = useState(16);
  const [column, setColumn] = useState(4);
  const intl = useIntl();

  useEffect(() => {
    fetchFileExt();
    if (props.gutter) {
      const { gutter, column } = props;
      setGutter(gutter);
      setColumn(column);
      setPageSize(column * 2);
      fetchDatas();
    } else {
      fetchDatas();
    }
  }, []);

  const fetchFileExt = async () => {
    const resp = await GetFileExt();
    const { ext } = props;
    if (resp?.result) {
      setFileExt(resp?.result.filter((item: any) => ext.indexOf(item) >= 0));
    }
  };

  const fetchDatas = () => {
    setLoading(true);
    const fileExt = ext ? ext : props.ext;
    request(apiURL + 'GetList', {
      method: 'GET',
      params: { SkipCount: (pageIndex - 1) * pageSize, MaxResultCount: pageSize, keywords, ext: fileExt },
    }).then((response) => {
      if (response && response.success) {
          setDataSource(response.result.items);
          setTotalCount(response.result.totalCount);
          setLoading(false);
      }
    });
  };

  const onSearch = (keywords: any) => {
    setKeywords(keywords);
    fetchDatas();
  };

  const onPageChange = (page: any, pageSize: any = 12) => {
    setPageIndex(page);
    setPageSize(pageSize);
    fetchDatas();
  };

  const signleSelect = (val: any) => {
    if (props.clickFun) {
      props.clickFun(val);
    }
  };

  const multiSelect = (e: any, item: any) => {
    let Ids: string[] = [...selectId];
    if (e.target.checked) {
      if (!Ids.includes(item.sysRowID)) {
        Ids.push(item.sysRowID);
        setSelectId(Ids);
      }
    } else {
      if (Ids.includes(item.sysRowID)) {
        Ids = Ids.filter(id => id !== item.sysRowID);
        setSelectId(Ids);
      }
    }
  };

  const doMultiSelect = () => {
    if (props.clickMultiFun) {
      props.clickMultiFun(selectId);
    }
  };

  const handleUpload = (info: any) => {
    fetchDatas();
  };

  const doDelete = () => {
    const arr = dataSource.filter((o: any) => selectId.includes(o.sysRowID));
    arr.forEach((item: any) => {
      request(apiURL + 'Remove', {
        method: 'DELETE',
        data: { id: item.id },
      });
    });
    fetchDatas();
  };

  const doRefresh = () => {
    setExt(null);
    fetchDatas();
  };

  const firstPZ = column * 2;

  return (
    <div>
      <Card>
        <Space>
          <Button
            type="primary"
            onClick={doRefresh}
            loading={loading}
            icon={<SyncOutlined />}
          >
            {intl.formatMessage({id: 'pages.refresh'})}
          </Button>
          <Select
            style={{ width: 100 }}
            placeholder={intl.formatMessage({id: 'pages.fileFormat'})}
            onChange={(value) => setExt(value)}
          >
            {fileExt
              ? fileExt.map((item: any) => (
                <Select.Option key={item} value={item}>
                  {item}
                </Select.Option>
              ))
              : null}
          </Select>
          <Search
            style={{ width: 160 }}
            placeholder={intl.formatMessage({id: 'pages.enterKeywords'})}
            onSearch={(value) => onSearch(value)}
          />
          <Upload
            action={UploadUtil.uploadOSS}
            headers={{
              Authorization: UploadUtil.accessToken,
            }}
            showUploadList={false}
            multiple={true}
            onChange={handleUpload}
          >
            <Button icon={<UploadOutlined />}>上传</Button>
          </Upload>
          <Button danger onClick={doDelete}>
            {intl.formatMessage({id: 'pages.delete'})}
          </Button>
          <Button type="primary" onClick={doMultiSelect}>
            {intl.formatMessage({id: 'pages.selected'})} {selectId.length} {intl.formatMessage({id: 'pages.PCS'})}
          </Button>
        </Space>
      </Card>
      <Card style={{ borderTop: 0 }}>
        <List
          grid={{ gutter, column }}
          dataSource={dataSource}
          renderItem={(item: any) => (
            <List.Item>
              <Card
                cover={
                  <img
                    alt={item.fileName}
                    src={item.fileUrl}
                    onClick={() => signleSelect(item.sysRowID)}
                  />
                }
              >
                <Checkbox onChange={(e: any) => multiSelect(e, item)} />
              </Card>
            </List.Item>
          )}
        />
        <Pagination
          defaultCurrent={pageIndex}
          pageSize={pageSize}
          total={totalCount}
          onChange={onPageChange}
          pageSizeOptions={[
            firstPZ.toString(),
            (firstPZ * 2).toString(),
            (firstPZ * 3).toString(),
            (firstPZ * 5).toString(),
          ]}
          showTotal={(total) => `${intl.formatMessage({id: 'pages.total'})} ${total} ${intl.formatMessage({id: 'pages.PCS'})}`}
        />
      </Card>
    </div>
  );
};

export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(ViewPage);
